<?php
/*
**Cus是customer的缩写，Cus类是Database类（数据库类）的继承类，同时集合了响应客户动作的函数
**
*/
include_once("./mysql.php");
class Cus extends Database{
	/*
	||	获取页面配置
	||	参数:无
	*/
	function getPageConfigData(){
		$results = array();
		$con = self::open();
		if($con){
			//Basic
			$re = self::$conn->query("select * from pageConfig");
			$arrInfo = mysqli_fetch_assoc($re);
			if($arrInfo==0){
				echo '{
				"re":"sql result empty!"
				}';
			}else{
				$results['basic'] = $arrInfo;
			}
			//Hot
			$re = self::$conn->query("select * from goods where gid in (select gid from pageConfigHot);");
			$arrInfo= array();
			while(true){
				$arr=mysqli_fetch_assoc($re);
				if($arr==0){
					break;
				}
				$arr['price'] = explode(' ',$arr['price']);
				$arr['specifications'] = explode(' ',$arr['specifications']);
				array_push($arrInfo,$arr);
			}
			if($arrInfo==0){
				echo '{
				"re":"sql result empty!"
				}';
			}else{
				$results['hot'] = $arrInfo;
			}
			//More
			$re = self::$conn->query("select * from goods where gid in (select gid from pageConfigMore);");
			$arrInfo= array();
			while(true){
				$arr=mysqli_fetch_assoc($re);
				if($arr==0){
					break;
				}
				$arr['price'] = explode(' ',$arr['price']);
				$arr['specifications'] = explode(' ',$arr['specifications']);				
				array_push($arrInfo,$arr);
			}
			if($arrInfo==0){
				echo '{
				"re":"sql result empty!"
				}';
			}else{
				$results['more'] = $arrInfo;
			}
			//将拼接的结果返回
			echo json_encode($results,JSON_UNESCAPED_UNICODE);
		}else{
			echo '{
			"re":"sqlServer Err!"
			}';
		}
		self::__destruct();
	}

	/*
	||	login 登录
	||	参数:[stirng:code],string:host_address
	*/
	function login($arr,$host_address){
		$code = $arr['code'];
		$addr = $host_address;
		//第一步，获取openid
		$remote_server = "https://api.weixin.qq.com/sns/jscode2session";
		$post_string="appid=wx6945f40fd5a17f52&secret=f6108c22d219b16536680517a353de9c&js_code=".$code."&grant_type=authorization_code";
		$ch = curl_init($remote_server."?".$post_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT_MS, 2000);
        $data = curl_exec($ch);
        $curl_errno = curl_errno($ch);
        $curl_error = curl_error($ch);
        curl_close($ch);
		
        if ($curl_errno > 0) {
        	//如果查询出错，则终止登录行为并返回报错信息
            echo "cURL Error ($curl_errno): $curl_error\n";
            return;
        } else {
			$dataArr = json_decode($data,true);
			$openid = $dataArr['openid'];
			//加密
			include_once('./Security.php');
			$openid = comHash($openid);
        }
        //第二步，查询注册并返回cid
        $con = self::open();
		if($con){
			//测试是否存在同样的openid
			$re = self::$conn->query("select cid from clientAccount where openid = '".$openid."'");
			$arr = mysqli_fetch_array($re);
			if($arr==false){
				//注册
				$re = self::$conn->query("insert into clientAccount(openid,username,profilePicUrl,gender,birthday,address)values ('".$openid."','微信用户','http://".$addr."/gallaryMarket/img/defaultPFpic.png',2,'隐藏','空')");
				//获得cid
				if($re){
					$getCidRe = self::$conn->query("select cid from clientAccount where openid = '".$openid."'");
					$cidArr = mysqli_fetch_array($getCidRe);
					echo '{
					"cid":"'.$cidArr[0].'"
					}';
				}else{
					echo '{
					"re":"After registed sql GetCid Err!"
					}';
				}
			}else{
				//已注册则直接返回cid
				echo '{
				"cid":"'.$arr[0].'"
				}';
			}
		}else{
			echo '{
			"re":"sqlErr"
			}';
		}
		self::__destruct();
	}

	/*
	||	autologin 自动登录
	||	参数:[string:openid]
	*/
	function autoLogin($arr){
		$openid = $arr['openid'];
		//查询并返回cid
        $con = self::open();
		if($con){
			$re = self::$conn->query("select cid from clientAccount where openid = '".$openid."'");
			$arr = mysqli_fetch_array($re);
			if($arr==0){
				echo 'No such token!';
			}else{
				echo '{
				"cid":"'.$arr[0].'"
				}';
			}
		}else{
			echo '{
			"re":"sqlErr"
			}';
		}
		self::__destruct();
	}

	/*
	||	查看基础个人信息
	||	参数:[int:cid]
	*/
	function checkBasicInfo($arr){
		$cid = $arr['cid'];
		$con = self::open();
		if($con){
			$re = self::$conn->query("select * from clientAccount where cid =".$cid);
			$arrInfo = mysqli_fetch_assoc($re);
			if($arrInfo==0){//如果为空则可能是cid问题
				echo "cidErr";
			}else{
				echo json_encode($arrInfo,JSON_UNESCAPED_UNICODE);
			}
			
		}else{
			echo '{
			"re":"sqlErr"
			}';
		}
		self::__destruct();
	}

	/*
	||	获得商品列表
	||	参数:[int:pageNo,int:typeIndex]
	*/
	function checkGoods($arr){
		$pageNo = $arr['pageNo'];
		$pageSize = 5;
		$typeIndex = $arr['typeIndex'];

		$start = ($pageNo-1)*$pageSize;
		switch($typeIndex){
			case 0:
				$goodclass="all";
				break;
			case 1:
				$goodclass = "画作";
				break;
			case 2:
				$goodclass = "明信片";
				break;
			case 3:
				$goodclass = "花瓶";
				break;
			default:
				echo '{
				"re":"gclassErr"
				}';
		}
		$con = self::open();
		if($con){
			if($goodclass == "all"){
				$re = self::$conn->query("select * from goods limit ".$start.",".$pageSize."");
			}else{
				$sqlString = "select * from goods where gtype = '".$goodclass."' limit ".$start.",".$pageSize;
				$re = self::$conn->query($sqlString);
			}
			$arrgoods= array();
			while(true){
				$arr=mysqli_fetch_assoc($re);
				if($arr==false){
					break;
				}
				$arr['price'] = explode(' ',$arr['price']);
				$arr['specifications'] = explode(' ',$arr['specifications']);				
				array_push($arrgoods,$arr);
			}
			echo json_encode($arrgoods,JSON_UNESCAPED_UNICODE);
		}else{
			echo '{
			"re":"sqlErr"
			}';
		}
		self::__destruct();
	}
	/*
	||	获得单个商品信息
	||	参数:[int:gid]
	*/
	function getGoodDetail($arr){
		$gid = $arr['gid'];
		$con = self::open();
		if($con){
			$re = self::$conn->query("select * from goods where gid = ".$gid);
			$arr=mysqli_fetch_assoc($re);
			if($arr==false){
				break;
			}			
			$arr['price'] = explode(' ',$arr['price']);
			$arr['specifications'] = explode(' ',$arr['specifications']);	
			echo json_encode($arr,JSON_UNESCAPED_UNICODE);
			
		}else{
			echo '{
			"re":"sqlErr"
			}';
		}
		self::__destruct();
	}
	/*
	||		添加购物车
	||	参数：[int:cid,int:gid,int:num,int:priceIndex]
	*/
	function addShopCart($arr){
		$cid = $arr['cid'];
		$gid = $arr['gid'];
		$num = $arr['num'];
		$priceIndex = $arr['priceIndex'];
		$con = self::open();
		if($con){
			//查询是否已存在
			$re=self::$conn->query("select gid from shopcart where gid = ".$gid);
			if($re==false){//如果存在则不执行任何操作
				return;
				self::__destruct();
			}
			//添加
			$sqlString = "insert into shopcart(cid,bid,gid,gtype,name,imgUrl,price,num,priceIndex) select ".$cid.",bid,gid,gtype,name,smallPicUrl,price,".$num.",".$priceIndex." from goods where gid=".$gid;
			self::$conn->query($sqlString);
			//返回新的购物车列表
			$re=self::$conn->query("select * from shopcart where cid = ".$cid);
			$arrCarts = array();
			while(true){
				$arr=mysqli_fetch_assoc($re);
				if($arr==0){
					break;
				}
				$arr['price'] = explode(' ',$arr['price']);
				array_push($arrCarts,$arr);
			}
			echo json_encode($arrCarts,JSON_UNESCAPED_UNICODE);			
		}else{
			echo '{
			"re":"sqlErr"
			}';
		}
		self::__destruct();
	}
	/*
	||		查看购物车
	||	参数：[int:cid]
	*/
	function checkShopCart($arr){
		$cid = $arr['cid'];
		$con = self::open();
		if($con){
			$re=self::$conn->query("select * from shopcart where cid = ".$cid);
			$arrCarts = array();
			while(true){
				$arr=mysqli_fetch_assoc($re);
				if($arr==0){
					break;
				}
				$arr['price'] = explode(' ',$arr['price']);
				array_push($arrCarts,$arr);
			}
			echo json_encode($arrCarts,JSON_UNESCAPED_UNICODE);
		}else{
			echo '{
			"re":"sqlErr"
			}';
		}
		self::__destruct();
	}
	/*
	||		购物车删除
	||	参数：[int:cid,string:gidString]
	*/
	function deleteShopCart($arr){
		$cid = $arr['cid'];
		$gidString = $arr['gidList'];
		$gidList = explode(' ',$gidString);
		$gidSqlString = implode(',',$gidList);
		$con = self::open();
		if($con){
			//删除
			$sqlString = "delete from shopcart where gid in (".$gidSqlString.") and cid = ".$cid;
			self::$conn->query($sqlString);
			//返回新的数据
			$re = self::$conn->query("select * from shopcart where cid = ".$cid);
			$arrCarts = array();
			while(true){
				$arr=mysqli_fetch_assoc($re);
				if($arr==0){
					break;
				}
				$arr['price'] = explode(' ',$arr['price']);
				array_push($arrCarts,$arr);
			}
			echo json_encode($arrCarts,JSON_UNESCAPED_UNICODE);
		}else{
			echo '{
			"re":"sqlErr"
			}';
		}
		self::__destruct();
	}
	
	
	/*
	||		添加订单
	||	参数:[String:orderList]
	*/
	function addOrder($arr){
		$orderArrObj = json_decode($arr['orderList']);
		$con = self::open();
		if($con){
			foreach($orderArrObj as $value){
				$sqlString = "CALL ClientAddOrderProcedure(".$value->cid.",".$value->bid.",".$value->gid.",".$value->num.",".$value->total.")";
				$re=self::$conn->query($sqlString);
				if($re==false){
					echo 'query Error';
				}				
			}
		}else{
			echo '{
			"re":"sqlErr"
			}';
		}
		self::__destruct();
	}

	/*
	||		查看订单
	||	参数:[Int:cid]
	*/
	function checkOrder($arr){
		$cid = $arr['cid'];
		$con = self::open();
		if($con){
			$sqlString = "CALL ClientCheckOrderProcedure(".$cid.")";
			$re=self::$conn->query($sqlString);
			if($re == false){
				echo "query error";
			}else{
				$arrList = array();
				while(true){
					$arr=mysqli_fetch_assoc($re);
					if($arr==0){
						break;
					}
					array_push($arrList,$arr);
				}
				echo json_encode($arrList,JSON_UNESCAPED_UNICODE);
			}
		}else{
			echo '{
			"re":"sqlErr"
			}';
		}
		self::__destruct();
	}

	/*
	||		确认订单
	||	参数:[Int:oid,Int:Cid]
	*/
	function comfirmOrder($arr){
		$cid = $arr['cid'];
		$oid = $arr['oid'];
		$con = self::open();
		if($con){
			$sqlString = "CALL ClientComOrderProcedure(".$oid.",".$cid.")";
			$re=self::$conn->query($sqlString);
			if($re == false){
				echo "query error";
			}
		}else{
			echo '{
			"re":"sqlErr"
			}';
		}
		self::__destruct();
	}

	/*
	||		查看购买记录
	||	参数:int cid
	*/
	function checkHistory($cid){
		$con = self::open();
		if($con){
			$re = self::$conn->query("select hid from history where cid =".$cid);
			$hidArr = array();
			if($re){
				while(true){
					$newArr = mysqli_fetch_assoc($re);
					if($newArr==0){
					break;
					}
					array_push($hidArr,$newArr);
				}
			}else{
				echo "re:0";
			}
			if(count($hidArr)==0){

			}else{
				$historyArr = array();
				foreach($hidArr as $value){
					$hid = $value['hid'];
					$re = self::$conn->query("select hid,hdata,num,total from history where hid =".$hid);
					$newhistoryArr = mysqli_fetch_assoc($re);
					
					$re = self::$conn->query("select gid from history where hid =".$hid);
					$gidArr = mysqli_fetch_array($re);
					$gid = $gidArr[0];
					
					$re = self::$conn->query("select sImage,name from goods where gid =".$gid);
					$detailArr = mysqli_fetch_assoc($re);
					
					$selectArr = array('select'=>true);
					
					$newhistoryArr=array_merge($newhistoryArr,$detailArr,$selectArr);
					array_push($historyArr,$newhistoryArr);
				}
				echo json_encode($historyArr,JSON_UNESCAPED_UNICODE);
			}
			
			
		}else{
			echo '{
			"re":"sqlErr"
			}';
		}
		self::__destruct();
			
	}
	/*
	||		发表评论
	||	参数:[int:cid,int:gid,string:words]
	*/
	function addComment($arr){
		$cid = $arr['cid'];
		$gid = $arr['gid'];
		$words = $arr['words'];
		if($words==''){
			echo "words is empty!";
			return;
		}
		$con = self::open();
		if($con){
			self::$conn->query("insert into comment (cid,gid,profilePicUrl,username,time,text) select ".$cid.",".$gid.",profilePicUrl,username,NOW(),'".$words."' from clientAccount where cid=".$cid);
		}else{
			echo '{
			"re":"sqlErr"
			}';
		}
		self::__destruct();
	}
	
	
	/*
	||		查看评论
	||	参数:[int:gid]
	*/
	function checkComment($arr){
		$gid = $arr['gid'];
		$con = self::open();
		if($con){
			$re=self::$conn->query("select * from comment where gid = ".$gid);
			$arrComment = array();
			while(true){
				$item=mysqli_fetch_assoc($re);
				if($item==0){
					break;
				}
				array_push($arrComment,$item);
			}
			echo json_encode($arrComment,JSON_UNESCAPED_UNICODE);
		}else{
			echo '{
			"re":"sqlErr"
			}';
		}
		self::__destruct();
	}

	/*
	||		更改头像
	||	参数:int cid
	*/
	function insertHimage($arr,$host_address){
		$cid = $arr['cid'];
		$fpath = "../img/profileImage/";
		$fname = $cid.".jpg";
		move_uploaded_file($_FILES['file']['tmp_name'],$fpath.$fname);
		$fileaddress = "http://".$host_address."/gallaryMarket/img/profileImage/".$fname;
		$con = self::open();
		if($con){
			self::$conn->query("update clientAccount set profilePicUrl = '".$fileaddress."' where cid = ".$cid);
			echo "1|".$fileaddress;
		}else{
			echo '{
			"re":"sqlErr"
			}';
		}
		self::__destruct();
	}

	/*
	||	更改个人资料
	||	参数:[string:submitInfo]
	*/
	function alterClientInfo($arr){
		$submitInfo = json_decode($arr['submitInfo'], true);
		$sqlString = '';
		foreach($submitInfo as $key=>$value){
			if($key=='cid') continue;//cid作为条件
			if($key=='gender'){//gender是int类型
				$sqlString = $sqlString.$key."=".$value.",";
			}else{//其余为varchar类型
				$sqlString = $sqlString.$key."='".$value."',";
			}
		}
		$sqlString = substr($sqlString, 0, -1);//剪掉最后的逗号
		$con = self::open();
		if($con){
			//更新
			$string = "update clientAccount set ".$sqlString." where cid = ".$submitInfo['cid'];//用来输出检查
			self::$conn->query($string);
			//返回新个人资料
			$re = self::$conn->query("select * from clientAccount where cid =".$submitInfo['cid']);
			$arrInfo = mysqli_fetch_assoc($re);
			if($arrInfo==0){
				echo "queryErr";
			}else{
				echo json_encode($arrInfo,JSON_UNESCAPED_UNICODE);
			}
		}else{
			echo '{
			"re":"sqlErr"
			}';
		}
		self::__destruct();
	}

	/*
	||	查找商品
	||	参数:[string:keyword]
	*/
	function searchGoods($arr){
		$keyword = $arr['keyword'];
		$page = $arr['page'];
		$pageLength = $arr['pageLength'];
		$con = self::open();
		if($con){
			$string = "call ClientSearchGoods('".$keyword."',".$page.",".$pageLength.")";
			$re = self::$conn->query($string);
			$arrgoods= array();
			while(true){
				$arr=mysqli_fetch_assoc($re);
				if($arr==false){
					break;
				}
				$arr['price'] = explode(' ',$arr['price']);
				$arr['specifications'] = explode(' ',$arr['specifications']);				
				array_push($arrgoods,$arr);
			}
			echo json_encode($arrgoods,JSON_UNESCAPED_UNICODE);
		}else{
			echo '{
			"re":"sqlErr"
			}';
		}
		self::__destruct();
	}
}

?>